package com.bigshen.algorithm.eTwoPointer.solution01TwoSum;

/**
 * 167. Two Sum II - Input array is sorted
 * Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
 *
 * The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
 *
 * Note:
 *
 * Your returned answers (both index1 and index2) are not zero-based.
 * You may assume that each input would have exactly one solution and you may not use the same element twice.
 *  
 *
 * Example 1:
 *
 * Input: numbers = [2,7,11,15], target = 9
 * Output: [1,2]
 * Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
 * Example 2:
 *
 * Input: numbers = [2,3,4], target = 6
 * Output: [1,3]
 * Example 3:
 *
 * Input: numbers = [-1,0], target = -1
 * Output: [1,2]
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class Solution {

    // 两种解决方案
    // 1. 暴力解法
    // 两层for循环，时间复杂度 O(N^2)
    // 2. 数组排序，双指针
    // 先将数组排序 O(logN)
    // 之后 头、尾 两指针相加，值过大则 end--，值过小则 start++  O(N)
    public int[] twoSum(int[] nums, int target) {

        if (null == nums || nums.length == 0) {
            return null;
        }

        //Arrays.sort(nums);

        int start = 0;
        int end = nums.length-1;

        while(start < end) {
            if (nums[start] + nums[end] > target) {
                // 值过大，变小
                end --;
            } else if (nums[start] + nums[end] < target) {
                // 值过小，变大
                start ++;
            } else {
                // 相等
                return new int[]{start+1,end+1};
            }
        }

        return new int[]{-1,-1};

    }

}

